﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

//Author: ljj
//Date: 20190613
//Function: 用于读取CSV文件
namespace Assets.Scripts.Utility
{
    class CSVData
    {
        private string[][] array;
        public int row;
        public int col;
        public CSVData(String path)
        {
            TextAsset binAsset = Resources.Load(path, typeof(TextAsset)) as TextAsset;
            String str = binAsset.text.Replace("\n", "");
            string[] lineArray = str.Split('\r');
            array = new string[lineArray.Length][];
            for (int i = 0; i < lineArray.Length; i++)
            {
                array[i] = lineArray[i].Split(',');
            }
            row = array.Length - 1; 
            col = array[0].Length;
            while (row > 0 && array[row].Length != col)
                --row;
            //Debug.Log("load CSV:"+path+" row=" + row.ToString() + " col=" + col.ToString()); 
        }

        private int nameToIndex(String name)
        {
            for (int i = 0; i < col;i++)
            {
                if (array[0][i].Equals(name))
                    return i;
            }
            return -1;
        }

        public String getData(int r,int c)
        {
            if (r >= 0 && r < row)
            {
                if (c >= 0 && c < array[r + 1].Length)
                {
                    return array[r + 1][c];
                }else
                {
                    //Debug.Log("Wrong col");
                    return "";
                }
            }
            else {
                //Debug.Log("Wrong row");
                return "";
            }
        }

        public String getData(int r, String name)
        {
            if (r >= 0 && r < row)
            {
                int c = nameToIndex(name);
                if (c >= 0 && c < array[r + 1].Length)
                {
                    return array[r + 1][c];
                }
                else
                {
                    //Debug.Log("Wrong name");
                    return "";
                }
            }
            else
            {
                //Debug.Log("Wrong row");
                return "";
            }
        }
    }
}
